//
//  Emoticon.swift
//  02-表情测试
//
//  Created by 唐万超 on 15/8/9.
//  Copyright © 2015年 唐万超. All rights reserved.
//

import UIKit

/// 表情包模型
class EmoticonPackage: NSObject {
    
    /// 目录名
    var id: String
    /// 分组名
    var groupName: String = ""
    /// 表情数组
    var emoticons: [Emoticon]?
    
    init(id: String) {
        self.id = id
    }
    
    /// 表情包的路径
    static let bundlePath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons.bundle")
    
    /// 加载所有表情包
    class func packages() -> [EmoticonPackage] {
        // 路径加载
        let path = bundlePath.stringByAppendingPathComponent("emoticons.plist")
        // 加载plist
        let dict = NSDictionary(contentsOfFile: path)!
        let array = dict["packages"] as! [[String : AnyObject]]
        
        // 遍历数组
        var arrayM = [EmoticonPackage]()
        for d in array {
            let id = d["id"] as! String
            let package = EmoticonPackage(id: id).loadEmoticons()
            
            arrayM.append(package)
        }
        return arrayM
    }
    
    /// 加载当前对象对应的表情数组，从info.plist中加载
    /// Self表示本类的对象
    func loadEmoticons() -> Self {
        let path = EmoticonPackage.bundlePath.stringByAppendingPathComponent(id).stringByAppendingPathComponent("info.plist")
        
        let dict = NSDictionary(contentsOfFile: path)!
        
        groupName = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String: String]]
        
        // 2. 遍历数组
        emoticons = [Emoticon]()
        for d in array {
            // 将表情包的 id 传递给 表情，方便拼接路径
            emoticons?.append(Emoticon(dict: d))
        }
        
        return self
    }
    
    override var description: String {
        return "\(id) \(groupName) \(emoticons)"
    }
    
}

/// 表情模型
class Emoticon: NSObject {
    
    /// 表情目录
    var id: String?
    
    /// 发送给服务器的表情文字
    var chs: String?
    /// 本地显示的图片
    var png: String?
    /// emoji的代码
    var code: String?
    
    init(dict: [String : AnyObject] )
    {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        return "\(chs) \(png) \(code)"
    }

}
